﻿using System;
using System.Reflection;
using System.ServiceModel;
using YawetagLib.Services;

namespace YawetagLib.ServiceModel
{
    public abstract class ServiceDispatcher : IDisposable
    {
        protected ServiceDispatcher(ServiceBroker serviceBroker)
        {
            ServiceBroker = serviceBroker;
        }

        protected ServiceDispatcher()
            : this(new ServiceBroker())
        {
        }

        protected TCallbacks GetCallbacks<TCallbacks>() where TCallbacks : ICallbacks
        {
            return OperationContext.Current.GetCallbackChannel<TCallbacks>();
        }

        protected void RegisterService<TService>() where TService : class, IService
        {
            ServiceBroker.RegisterService<TService>();
        }

        protected void RegisterServices(Assembly assembly)
        {
            ServiceBroker.RegisterServices(assembly);
        }

        protected TService At<TService>() where TService : IService
        {
            return ServiceBroker.Get<TService>();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
                if (disposing)
                {
                    ManagedResourceCleanup();
                }
                UnmanagedResourceCleanup();
                IsDisposed = true;
            }
        }

        protected virtual void ManagedResourceCleanup()
        {
            ServiceBroker.Dispose();
        }

        protected virtual void UnmanagedResourceCleanup()
        {
        }

        ~ServiceDispatcher()
        {
            Dispose(false);
        }

        private ServiceBroker ServiceBroker { get; set; }

        private bool IsDisposed { get; set; }
    }
}
